<template>
	<view class="container">
		<view class="title">账号登录</view>

		<!-- 标签页切换 -->
		<view class="tabs">
			<view class="tab-item" :class="{ active: currentTab === 0 }" @click="currentTab = 0">
				账号登录
			</view>
			<view class="tab-item" :class="{ active: currentTab === 1 }" @click="currentTab = 1">
				账号注册
			</view>
		</view>

		<!-- 表单内容 -->
		<form class="form" @submit.prevent="handleSubmit">
			<!-- 登录表单 -->
			<view v-if="currentTab === 0">
				<view class="input-item">
					<input 
						type="text" 
						v-model="loginForm.account" 
						placeholder="请输入账号" 
						class="input" 
						required 
						@input="handleAccountInput('login')"
					/>
				</view>
				<view class="input-item">
					<input type="password" v-model="loginForm.password" placeholder="请输入密码" class="input" required />
				</view>
				<button form-type="submit" class="btn primary" :loading="loading">
					登录
				</button>
				<button class="btn wechat" @click="wechatLogin" :loading="wechatLoading">
					<uni-icons type="weixin" size="24" color="#fff"></uni-icons>
					微信快捷登录
				</button>
			</view>

			<!-- 注册表单 -->
			<view v-if="currentTab === 1">
				<!-- 头像区域 -->
				<view class="avatar-section">
					<view class="section-title">头像</view>
					<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
						<view class="avatar-container">
							<image 
								class="avatar" 
								:src="avatarUrl" 
								mode="aspectFill"
								@error="handleImageError"
							></image>
							<view class="avatar-overlay" hover-class="avatar-overlay-hover">
								<view class="avatar-action">
									<text class="action-text">更换</text>
								</view>
							</view>
							<view class="avatar-placeholder" v-if="!hasAvatar && !isLoading">
								<text class="avatar-placeholder-text">+</text>
							</view>
							<view class="avatar-loading" v-if="isLoading">
								<uni-loading-icon size="24" color="#666"></uni-loading-icon>
							</view>
						</view>
					</button>
					<text class="avatar-tips">支持JPG、PNG格式，建议尺寸200x200px</text>
					<text class="avatar-error" v-if="imageError">{{ imageError }}</text>
				</view>

				<view class="input-item">
					<input 
						type="text" 
						v-model="registerForm.nickname" 
						placeholder="请输入昵称（不支持空格）" 
						class="input" 
						@input="handleNicknameInput"
						maxlength="20" 
						required 
					/>
				</view>

				<view class="input-item">
					<input 
						type="text" 
						v-model="registerForm.account" 
						placeholder="请设置账号（仅支持字母和数字）" 
						class="input" 
						required 
						@input="handleAccountInput('register')"
						maxlength="20"
					/>
				</view>

				<view class="input-item">
					<input 
						type="password" 
						v-model="registerForm.password" 
						placeholder="请设置密码（至少6位）" 
						class="input" 
						required 
						maxlength="20"
					/>
				</view>

				<view class="error-tip" v-if="errorMsg">{{ errorMsg }}</view>

				<button form-type="submit" class="btn primary" :loading="loading" :disabled="!canSubmit">
					注册（自动绑定微信）
				</button>
				<view class="tip">
					注册即表示同意绑定当前微信账号
				</view>
			</view>
		</form>
	</view>
</template>

<script>
	import { NEW_URL_DEV } from "@/common/config.js";
	export default {
		data() {
			return {
				currentTab: 0,
				loading: false,
				wechatLoading: false,
				errorMsg: '',
				loginForm: {
					account: '',
					password: ''
				},
				registerForm: {
					account: '',
					nickname: '',
					password: '',
					openid: '',
					avatarUrl: ''
				},
				globalOpenid: '',
				defaultAvatar: '/static/images/avatar-default.png',
				localAvatarPath: '',
				isLoading: false,
				imageError: ''
			};
		},
		computed: {
			canSubmit() {
				const accountValid = /^[A-Za-z0-9]{3,20}$/.test(this.registerForm.account);
				return accountValid && 
					   this.registerForm.password.trim().length >= 6 &&
					   this.registerForm.nickname.trim().length >= 2;
			},
			hasAvatar() {
				return !!this.localAvatarPath;
			},
			avatarUrl() {
				if (this.localAvatarPath) return this.localAvatarPath;
				return this.defaultAvatar;
			}
		},
		onLoad() {
			this.showToast = this.showToast.bind(this);
			this.getOpenid();
		},
		methods: {
			navigateBack() {
				uni.navigateBack({ delta: 1 });
			},

			async getOpenid() {
				try {
					const { code } = await uni.login({
						provider: 'weixin'
					});
					if (!code) {
						this.showToast('微信授权失败');
						return;
					}

					const res = await uni.request({
						url: NEW_URL_DEV + '/api/wx/getOpenid',
						method: 'POST',
						data: { code }
					});

					const responseData = res.data || res[1]?.data;
					if (responseData?.success) {
						this.globalOpenid = responseData.data.openid;
						this.registerForm.openid = this.globalOpenid;
					} else {
						this.showToast(responseData?.msg || '获取微信信息失败');
					}
				} catch (err) {
					console.error('获取openid失败:', err);
					this.showToast('微信授权异常，请稍后重试');
				}
			},

			showToast(message, icon = 'none', duration = 2000) {
				uni.showToast({
					title: message,
					icon: icon,
					duration: duration
				});
			},

			onChooseAvatar(e) {
				if (e.detail.avatarUrl) {
					this.isLoading = true;
					this.imageError = '';
					let tempUrl = e.detail.avatarUrl;
					
					// 处理微信小程序的临时路径
					if (tempUrl.startsWith('wxfile://')) {
						uni.getFileSystemManager().readFile({
							filePath: tempUrl,
							encoding: 'base64',
							success: (res) => {
								this.localAvatarPath = `data:image/png;base64,${res.data}`;
								this.isLoading = false;
								this.showToast('头像已选择', 'success');
							},
							fail: (err) => {
								console.error('读取头像文件失败:', err);
								this.imageError = '头像加载失败，请重试';
								this.isLoading = false;
							}
						});
					} else {
						this.localAvatarPath = tempUrl;
						this.isLoading = false;
						this.showToast('头像已选择', 'success');
					}
				} else {
					this.showToast('获取头像失败');
				}
			},
			
			handleImageError(e) {
				console.error('头像加载失败:', e);
				this.imageError = '头像显示失败，请重新选择';
				this.localAvatarPath = '';
			},

			handleNicknameInput(e) {
				const value = e.detail.value.replace(/\s+/g, '');
				this.registerForm.nickname = value;
			},

			handleAccountInput(formType) {
				const value = this[`${formType}Form`].account;
				const filteredValue = value.replace(/[^A-Za-z0-9]/g, '');
				this[`${formType}Form`].account = filteredValue;
			},

			async uploadAvatar(tempFilePath) {
				return new Promise((resolve, reject) => {
					if (!tempFilePath) {
						reject(new Error('头像文件路径为空'));
						return;
					}
					
					console.log('开始上传头像，临时路径:', tempFilePath);
					console.log('上传接口地址:', `${NEW_URL_DEV}/upload`);
					
					uni.uploadFile({
						url: `${NEW_URL_DEV}/upload`,
						filePath: tempFilePath,
						name: 'file',
						header: {
							'Content-Type': 'multipart/form-data'
						},
						success: (res) => {
							console.log('上传响应状态码:', res.statusCode);
							console.log('上传响应原始数据:', res.data);
							
							try {
								let data = res.data;
								if (typeof data === 'string') {
									data = JSON.parse(data);
								}
								
								if (res.statusCode === 200) {
									if (data.success) {
										if (data.avatarUrl) {
											resolve({ success: true, url: data.avatarUrl });
										} else {
											reject(new Error('服务器未返回头像URL'));
										}
									} else {
										reject(new Error(`上传失败: ${data.message || '未知错误'}`));
									}
								} else {
									reject(new Error(`服务器错误: ${res.statusCode}`));
								}
							} catch (e) {
								reject(new Error('解析响应失败: ' + e.message));
							}
						},
						fail: (err) => {
							console.error('上传API调用失败:', err);
							reject(new Error('上传失败: ' + (err.errMsg || '网络异常')));
						}
					});
				});
			},

			async handleSubmit() {
				if (this.currentTab === 1 && !this.globalOpenid) {
					this.showToast('请先完成微信授权');
					await this.getOpenid();
					return;
				}

				if (this.currentTab === 1) {
					if (/\s+/.test(this.registerForm.nickname)) {
						this.errorMsg = '昵称不支持空格，请重新输入';
						return;
					}
					if (!/^[A-Za-z0-9]{3,20}$/.test(this.registerForm.account)) {
						this.errorMsg = '账号必须包含3-20位字母或数字';
						return;
					}
					if (this.registerForm.password.trim().length < 6) {
						this.errorMsg = '密码长度不能少于6位';
						return;
					}
				}

				this.loading = true;
				this.errorMsg = '';
				try {
					let url = '';
					let data = {};
					let successMsg = '';

					if (this.currentTab === 0) {
						url = NEW_URL_DEV + '/api/auth/login';
						data = this.loginForm;
						successMsg = '登录成功，正在进入...';
					} else {
						url = NEW_URL_DEV + '/api/auth/register';
						let avatarUrl = this.defaultAvatar;
						
						if (this.localAvatarPath) {
							this.showToast('正在上传头像...', 'loading');
							try {
								const uploadRes = await this.uploadAvatar(this.localAvatarPath);
								avatarUrl = uploadRes.url;
							} catch (uploadErr) {
								this.showToast(`头像上传失败: ${uploadErr.message}，将使用默认头像`, 'none');
								console.warn('头像上传失败:', uploadErr);
							}
						}

						data = {
							...this.registerForm,
							avatarUrl: avatarUrl
						};
						
						successMsg = '注册成功，请登录';
					}

					const res = await uni.request({
						url,
						method: 'POST',
						data
					});
					const responseData = res.data || res[1]?.data;

					if (responseData?.success) {
						this.showToast(successMsg, 'success');

						if (this.currentTab === 0) {
							const userData = {
								account: responseData.data.account,
								nickname: responseData.data.nickname || responseData.data.account,
								openid: this.globalOpenid,
								token: responseData.data.token,
								role: responseData.data.role || '玩家',
								avatarUrl: responseData.data.avatarUrl || this.defaultAvatar
							};
							uni.setStorageSync('userData', userData);

							setTimeout(() => {
								uni.switchTab({
									url: '/pages/mine/mine'
								});
							}, 1500);
						} else {
							this.currentTab = 0;
						}
					} else {
						throw new Error(responseData?.msg || '操作失败');
					}
				} catch (err) {
					this.errorMsg = err.message;
					this.showToast(err.message, 'none');
				} finally {
					this.loading = false;
				}
			},

			async wechatLogin() {
				if (!this.globalOpenid) {
					this.showToast('请先完成微信授权');
					await this.getOpenid();
					return;
				}

				this.wechatLoading = true;
				try {
					const res = await uni.request({
						url: NEW_URL_DEV + '/api/auth/login/wechat',
						method: 'POST',
						data: {
							openid: this.globalOpenid
						}
					});

					const responseData = res.data || res[1]?.data;
					if (responseData?.success) {
						this.showToast('登录成功，正在进入...', 'success');
						const userData = {
							account: responseData.data.account,
							nickname: responseData.data.nickname || responseData.data.account,
							openid: this.globalOpenid,
							token: responseData.data.token,
							role: responseData.data.role || '玩家',
							avatarUrl: responseData.data.avatarUrl || this.defaultAvatar
						};
						uni.setStorageSync('userData', userData);

						setTimeout(() => {
							uni.switchTab({
								url: '/pages/mine/mine'
							});
						}, 1500);
					} else {
						this.showToast(responseData?.msg || '登录失败');
						if (responseData?.msg?.includes('未注册')) {
							this.currentTab = 1;
						}
					}
				} catch (err) {
					this.showToast('微信登录异常');
				} finally {
					this.wechatLoading = false;
				}
			}
		}
	};
</script>

<style scoped>
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding: 20rpx 30rpx;
		box-sizing: border-box;
	}

	.title {
		font-size: 48rpx;
		font-weight: bold;
		text-align: center;
		margin: 30rpx 0 60rpx;
		color: #333;
	}

	.tabs {
		display: flex;
		border-bottom: 1px solid #eee;
		margin-bottom: 40rpx;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		padding: 20rpx 0;
		font-size: 32rpx;
		color: #666;
		position: relative;
	}

	.tab-item.active {
		color: #3274e5;
		font-weight: bold;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: -1px;
		left: 0;
		width: 100%;
		height: 4rpx;
		background-color: #3274e5;
	}

	.form {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.input-item {
		display: flex;
		align-items: center;
		background-color: #fff;
		border-radius: 10rpx;
		padding: 0 20rpx;
		height: 80rpx;
		border: 1px solid #eee;
	}

	.input {
		flex: 1;
		height: 100%;
		font-size: 28rpx;
		color: #333;
		border: none;
		outline: none;
	}

	.btn {
		height: 90rpx;
		line-height: 90rpx;
		font-size: 32rpx;
		border-radius: 10rpx;
		margin-top: 20rpx;
		border: none;
		outline: none;
	}

	.primary {
		background-color: #3274e5;
		color: #fff;
	}

	.wechat {
		background-color: #07c160;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 10rpx;
	}

	.tip {
		font-size: 24rpx;
		color: #999;
		text-align: center;
		margin-top: 20rpx;
	}

	.avatar-section {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.section-title {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 15rpx;
		align-self: flex-start;
	}

	.avatar-wrapper {
		width: 160rpx;
		height: 160rpx;
		border-radius: 50%;
		overflow: hidden;
		margin-bottom: 15rpx;
		background: transparent;
		padding: 0;
		border: none;
	}

	.avatar-container {
		position: relative;
		width: 160rpx;
		height: 160rpx;
		border-radius: 50%;
		overflow: hidden;
	}

	.avatar {
		width: 100%;
		height: 100%;
		object-fit: cover;
		border-radius: 50%;
	}

	.avatar-placeholder {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f5f5f5;
		border-radius: 50%;
	}

	.avatar-placeholder-text {
		font-size: 60rpx;
		color: #999;
	}

	.avatar-loading {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(255, 255, 255, 0.8);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.avatar-overlay {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0);
		display: flex;
		align-items: center;
		justify-content: center;
		transition: background-color 0.3s;
	}

	.avatar-overlay-hover {
		background-color: rgba(0, 0, 0, 0.3);
	}

	.avatar-action {
		opacity: 0;
		transition: opacity 0.3s;
	}

	.avatar-overlay-hover .avatar-action {
		opacity: 1;
	}

	.action-text {
		color: white;
		font-size: 28rpx;
	}

	.avatar-tips {
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
	}

	.avatar-error {
		font-size: 24rpx;
		color: #ff5252;
		margin-top: 10rpx;
	}

	.error-tip {
		color: #ff5252;
		font-size: 24rpx;
		padding: 10rpx 0;
		text-align: center;
	}
</style>
    